import React from 'react';
import { Input , icon ,Button ,Table } from 'antd';
import './index.less';
const TextArea = Input.TextArea;


export default class TableForm extends React.Component{
    state = {
        data:[],
    }
    index = 0;
    componentWillMount(){
        const columnsInfo = this.props.columnsInfo;
        let columns = [];
        columnsInfo.map((item)=>{
            columns.push({
                title:item.title,
                dataIndex:item.dataIndex,
                key:item.key,
                render: (text, record) => {
                    return (
                        <TextArea
                            onChange={e => this.handleFieldChange(e, item.dataIndex ,record.key)}
                            value={text}
                            placeholder={text}
                            autosize
                        />
                    );
                },
            })
        })
        columns.push({
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            render: (text, record) => {
                return (
                    <a className="btn-txt-primary" onClick={()=>this.handelDel(record)}>删除</a>
                );
            },
        })
        this.setState({
            columns
        })
    }
    handleAdd = ()=>{
        let itemObj = {};
        this.state.columns.map((item)=>{
            console.log(item)
            itemObj[item.dataIndex] = ""
        })
        itemObj.key = `new${this.index}`
        this.index += 1;
        let data = this.state.data;
        data.push(itemObj);
        this.setState({ data });
    }
    handelDel = (record)=>{
        const { data } = this.state;
        const newData = data.filter(item => item.key !== record.key);
        this.setState({ data: newData },()=>{
            this.props.getData(this.state.data)
        });

    }
    handleFieldChange(e, dataIndex, key) {
        const { data } = this.state;
        let newData = [];
        data.map((item)=>{
            if (key==item.key){
                item[dataIndex] = e.target.value;
            }
            newData.push(item);
        })
        this.setState({ data: newData },()=>{
            this.props.getData(this.state.data)
        });
    }
    render(){

        return(
            <div>
                <Table
                    columns={this.state.columns}
                    dataSource={this.state.data}
                    pagination={false}
                />
                <Button
                    style={{ width: '100%', marginTop: 16, marginBottom: 8 }}
                    type="dashed"
                    onClick={this.handleAdd}
                    icon="plus"
                >
                    新增
                </Button>
            </div>
        )
    }
}